import { ip } from "./utils";
import axios from "axios";

export default class MapEditor {
  public map_name: string;
  private res: any;
  private image: Image;
  private stage: any;

  constructor(map_name: string, stage: any) {
    this.map_name = map_name || "";
    this.stage = stage;
  }

  public async openMap(): Promise<void> {
    this.res = await this.getMapData();
    this.image = this._arrayBufferToImageData(this.res);
    this.displayImage(this.image);
  }

  private getMapData(): Promise<ArrayBuffer> {
    return axios
      .get("http://" + ip("4000/map/" + this.map_name + ".pgm"), {
        responseType: "arraybuffer"
      })
      .then(response => {
        if (!(response.data instanceof ArrayBuffer)) {
          throw new Error("Expected ArrayBuffer");
        }
        return response.data;
      });
  }

  private _arrayBufferToImageData(arrayBuffer: ArrayBuffer): Image {
    const view = new DataView(arrayBuffer);
    let i = 0;
    if (view.getUint8(i++) != 80 || view.getUint8(i++) != 53) {
      console.log("---非pgm--");
      return;
    }
    i++;
    let c = view.getUint8(i++);
    if (c == 35) {
      do {
        c = view.getUint8(i++);
      } while (c != 10 && c != 13);
      c = view.getUint8(i++);
    }
    if (c < 48 || c > 57) {
      console.log("---读取宽错误--:" + c);
      return;
    }
    let k = 0;
    do {
      k = k * 10 + c - 48;
      c = view.getUint8(i++);
    } while (c >= 48 && c <= 57);
    const width = k;
    c = view.getUint8(i++);
    if (c < 48 || c > 57) {
      console.log("---读取高错误--:" + c);
      return;
    }
    k = 0;
    do {
      k = k * 10 + c - 48;
      c = view.getUint8(i++);
    } while (c >= 48 && c <= 57);
    const height = k;
    c = view.getUint8(i++);
    if (c < 48 || c > 57) {
      console.log("---读取灰度错误--:" + c);
      return;
    }
    k = 0;
    do {
      k = k * 10 + c - 48;
      c = view.getUint8(i++);
    } while (c >= 48 && c <= 57);
    // 解析像素数据
    const imageData = new ImageData(width, height);
    for (let y = 0; y < height; y++) {
      for (let x = 0; x < width; x++) {
        const gray = view.getUint8(i);
        imageData.data[(y * imageData.width + x) * 4] = gray;
        imageData.data[(y * imageData.width + x) * 4 + 1] = gray;
        imageData.data[(y * imageData.width + x) * 4 + 2] = gray;
        imageData.data[(y * imageData.width + x) * 4 + 3] = 255;
        i++;
      }
    }
    // 创建画布并绘制图像
    const imagecanvas = this.stage.canvas;
    imagecanvas.width = width;
    imagecanvas.height = height;
    const ctx = imagecanvas.getContext("2d");
    ctx.putImageData(imageData, 0, 0);
    const image = new Image();
    image.src = imagecanvas.toDataURL();
    return image;
  }

  private displayImage(image: Image): void {
    const bitmap = new createjs.Bitmap(image);
    this.stage.addChild(bitmap);
    this.stage.update();
  }
}
